package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/urfave/cli/v2"
)

// memoFile 是存储备忘录的文本文件的名称
const memoFile = "memo.txt"

func main() {
	app := &cli.App{
		Name:  "MemoApp",
		Usage: "A simple command line memo application",
		// 配置多组命令
		Commands: []*cli.Command{
			{
				Name:  "add",
				Usage: "Add a new memo",
				Action: func(c *cli.Context) error {
					memo := c.Args().First()
					if memo == "" {
						fmt.Println("输入备忘项为空 添加失败")
						return nil
					}
					err := addMemo(memo)
					if err != nil {
						fmt.Printf("写入备忘录失败: %s\n", err)
						return err
					}
					fmt.Println("添加备忘项成功")
					return nil
				},
			},
			{
				Name:  "list",
				Usage: "List all memos",
				Action: func(c *cli.Context) error {
					memo, err := listMemos()
					if err != nil {
						fmt.Printf("读取备忘录失败: %s\n", err)
						return nil
					}
					for i, memo := range memo {
						fmt.Printf("%d. %s\n", i+1, memo)
					}
					return nil
				},
			},
			{
				Name:  "delete",
				Usage: "Delete a memo",
				Action: func(c *cli.Context) error {
					memo := c.Args().First()
					err := deleteMemo(memo)
					if err != nil {
						fmt.Printf("删除备忘录失败: %s\n", err)
					}
					fmt.Printf("删除第%s条备忘录成功\n", memo)
					return nil
				},
			},
		},
	}

	err := app.Run(os.Args)
	if err != nil {
		fmt.Println(err)
	}
}

// 添加备忘录逻辑
func addMemo(memo string) error {
	// 打开备忘录文件，没有就创建一个
	file, err := os.OpenFile(memoFile, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
	if err != nil {
		return err
	}

	defer func(file *os.File) {
		err := file.Close()
		if err != nil {
			panic(err)
		}
	}(file)

	// 向备忘录文件中写入内容
	writer := bufio.NewWriter(file)
	conf := time.Now().Format("2006-01-02 15:04:05")
	_, err = writer.WriteString(fmt.Sprintf("%s   (写入时间: %s)\n", memo, conf))
	if err != nil {
		return err
	}

	err = writer.Flush()
	if err != nil {
		return err
	}
	return nil
}

// 列出所有备忘项
func listMemos() ([]string, error) {
	file, err := os.Open(memoFile)
	if err != nil {
		return nil, err
	}
	defer func(file *os.File) {
		err := file.Close()
		if err != nil {
			panic(err)
		}
	}(file)

	var memos []string
	// 逐行扫描数据
	scanner := bufio.NewScanner(file)
	// 调用scanner.Scan()方法读取文件下一行数据
	for scanner.Scan() {
		memos = append(memos, scanner.Text())
	}

	if err := scanner.Err(); err != nil {
		return nil, err
	}

	return memos, nil
}

// 删除指定备忘项
func deleteMemo(index string) error {
	file, err := os.OpenFile(memoFile, os.O_RDWR, 0644)
	if err != nil {
		return err
	}
	defer func(file *os.File) {
		err := file.Close()
		if err != nil {
			panic(err)
		}
	}(file)

	memos, err := listMemos()
	if err != nil {
		return err
	}

	i := 0
	for i < len(memos) {
		if strings.TrimSpace(index) == fmt.Sprintf("%d", i+1) {
			memos = append(memos[:i], memos[i+1:]...)
			break
		}
		i++
	}

	err = file.Truncate(0)
	if err != nil {
		return err
	}
	_, err = file.Seek(0, 0)
	if err != nil {
		return err
	}

	for _, memo := range memos {
		_, err := fmt.Fprintf(file, "%s\n", memo)
		if err != nil {
			return err
		}
	}

	return nil
}
